from common.libs.member.CartService import CartService
from common.libs.Helper import selectFilterObj
from common.libs.Helper import getDictFilterFiled
from common.libs.UrlManager import UrlManager
from common.models.cart import MemberCart
from common.models.food import Food
from web.controllers.api import route_api
from flask import request, g, jsonify
import json



@route_api.route('/cart/add', methods=['POST'])
def AddCart():
    resp = request.values
    res = {'code': 200, 'msg': '操作成功', 'data': {}}
    food_id = resp.get('id', type=int)
    change_number = resp.get('number', type=int)
    current_member = g.current_member

    if not current_member:
        res['code'] = -1
        res['msg'] = '请先登入！'
        return jsonify(res)

    if food_id < 1:
        res['code'] = -1
        res['msg'] = '加入购物车失败'
        return jsonify(res)

    member_id = g.current_member.id
    result = CartService.setItem(member_id, food_id, change_number)
    if not result:
        res['code'] = -1
        res['msg'] = '加入购物车失败'
        return jsonify(res)

    # 改变购物车美食的数量
    shopCarNum = MemberCart.query.filter_by(member_id=member_id).count()
    res['data']['shopCarNum'] = shopCarNum
    return jsonify(res)

@route_api.route('/cart/index')
def CartIndex():
    res = {'code': 200, 'msg': '操作成功', 'data': {}}
    current_member = g.current_member
    if not current_member:
        res['code'] = -1
        res['msg'] = '请先登入！'
        return jsonify(res)
    cart_info_list = []
    cart_list =MemberCart.query.filter_by(member_id = current_member.id).all()
    if cart_list:
        food_id_list = selectFilterObj(cart_list,'food_id')
        food_info =getDictFilterFiled(Food,Food.id,'id',food_id_list)
        for item in cart_list:
            food = food_info[item.food_id]
            cart_info ={
                "id": item.id,
                "food_id": item.food_id,
                "name": food.name,
                "price": str(food.price),
                "active": True,
                "number": item.quantity,
                "stock":food.stock, # 返回库存进行判断
                "pic_url": UrlManager.buildImageUrl(food.main_image),
            }
            cart_info_list.append(cart_info)
    res['data']['list']=cart_info_list
    return jsonify(res)


@route_api.route('/cart/del',methods=['POST'])
def DelCart():
    res = {'code': 200, 'msg': '操作成功', 'data': {}}
    resp = request.values
    goods = resp.get('goods')
    goods_list = json.loads(goods)
    current_member = g.current_member
    if not current_member:
        res['code'] = -1
        res['msg'] = '账号异常，请重新登入！'
        return jsonify(res)

    result = CartService.delItem(current_member.id,goods_list)
    if not result:
        res['code'] = -1
        res['msg'] = '删除失败！'
        return jsonify(res)

    return jsonify(res)

